package com.locoboard;

import java.io.UnsupportedEncodingException;

import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;

import com.google.gson.Gson;

import android.os.AsyncTask;
import android.widget.Toast;

/**
 * Post a message to the server in a background thread.
 * @author Gordon Meyer 03/13
 */
public class PostMessage extends AsyncTask<String,Void,String>{

	/**
	 * Will make an HTTP Post request of the server.
	 * Runs in a separate thread in the background.
	 * params[0] contains the message to be posted.
	 */
	@Override
	protected String doInBackground(String... params) {
		if(params == null || params[0] == null || params[0].equals("")){
			return "Malformed Post Message";
		}
		
		if(PositionManager.getLocation() == null){
			return "Unable to Find Location";
		}
				
		String url = Globals.SERVER_ADD + ":" + Globals.SERVER_PORT;
		
		// Transform message into JSON string for transmission.
		Gson gson = new Gson();		
		Post p = new Post(params[0]);	
		String data = gson.toJson(p);
		
				
		HttpParams hp = new BasicHttpParams();
		HttpConnectionParams.setConnectionTimeout(hp, Globals.CON_TIME_OUT);
		HttpConnectionParams.setSoTimeout(hp, Globals.SOC_TIME_OUT);
		
		HttpClient client = new DefaultHttpClient(hp);
		HttpPost httpPost = new HttpPost(url);
		
		// encode the JSON string
		StringEntity entity = null;
		try {
			entity = new StringEntity(data, HTTP.UTF_8);
		} catch (UnsupportedEncodingException e1) {
			return "Unable to Encode json";
		}
		
		if(entity != null){
			httpPost.setEntity(entity);			
			try {
				client.execute(httpPost);
			} catch (Exception ex){
				//return ex.toString();
				return "Unable to contact Server.";
			}
		}
		
		return null;
	}
	
	/**
	 * Executes on main thread after HTTP request is finished.
	 * If there was an error display it to the user, else
	 * signal post completion.
	 */
	@Override
	protected void onPostExecute(String response){
		if(response != null){	// post failure
			Toast.makeText(Globals.getContext(), response,
			        Toast.LENGTH_SHORT).show();
			MessageManager.onPostComplete(false);
		} else {				// post success
			MessageManager.onPostComplete(true);
		}
	}

}
